package genesis.familytree.server.common.code.builder;

import genesis.familytree.server.common.code.*;
import genesis.familytree.server.common.exception.ExpressionException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 */
public class TimeExprBuilder extends AbstractDataTypeBuilder implements DataTypeBuilder, DataNameBuilder {

    private static final String _NOW_NAME = "\1\5\2^(_@_NOW_)$\3";

    @Override
    public String build(String name, String format, Params params) throws ExpressionException {

        Object obj = null;
        if (_NOW_NAME.equals(name)) {
            obj = new Date();
        }else {
            obj = getValue(name, params);
        }

        if (null == format) {
            throw new IllegalArgumentException("["+ name +"] date format not found");
        }

        DateFormat df = new SimpleDateFormat(format);
        return df.format(obj);
    }

    @Override
    public Attribute build(Expression expr, int startIndex, int endIndex, String expression) {
        if (!expression.contains(":")) {
            return null;
        }

        String[] attrs = expression.split(":", 3);
        String name = attrs[0];
        String dataType;
        String format;
        if ("now".equals(name)) {
            name = _NOW_NAME;
            dataType = "date";
            format = attrs[1];
        }else {
            if (attrs.length != 3) {
                return null;
            }

            dataType = attrs[1];
            if (!"date".equals(dataType)) {
                return null;
            }
            format = attrs[2];
        }

        return new Attribute(expr, startIndex, endIndex, name, dataType, format);
    }
}
